import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  ImageBackground,
  Button,
  ToastAndroid,
} from 'react-native';
import { TextInput,  Switch } from 'react-native-paper';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { loginUser } from '../util/api';
import Loading from './compenent/Loading';

class LoginScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      isAdmin: false,
      loading: false,
    };
  }

  handleLogin = async () => {
    const { username, password, isAdmin } = this.state;
    // 处理登录逻辑
    console.log('Username:', username);
    console.log('Password:', password);
    console.log('Is Admin:', isAdmin);
    this.setState({ loading: true });

    loginUser(username, password, isAdmin).then(async res => {
      console.log(res);
      if (res.code == 0) {
        // 本地缓存管理员信息
        global.USER.isadmin = isAdmin
        global.USER.username = username

        await AsyncStorage.setItem('isAdmin', isAdmin ? 'true' : 'false');
        this.props.navigation.replace('Index', { isAdmin: isAdmin });
      } else {
        ToastAndroid.show(`登录失败:${res.msg}`, 2000);
      }
    })
      .finally(() => {
        this.setState({ loading: false });
      });
  };

  render() {
    return (
      <ImageBackground
        source={require('../assets/images/background.jpg')} // 替换为您自己的背景图路径
        style={styles.container}
        imageStyle={{ opacity: 0.7 }} // 修改透明度，范围为0（完全透明）到1（完全不透明）
      >
        <Loading loading={this.state.loading} />
        {/* <View style={styles.container}> */}
        <Image
          style={{
            width: 259,
            height: 238,
            marginTop: -250,
            marginBottom: 10,
            alignSelf: 'center',
          }}
          source={require('../assets/images/logo1.png')}
        />
        <TextInput
          label="用户名"
          value={this.state.username}
          onChangeText={text => this.setState({ username: text })}
        />
        <TextInput
          label="密码"
          value={this.state.password}
          onChangeText={text => this.setState({ password: text })}
          secureTextEntry
        />
        <View style={styles.checkboxContainer}>
          <Text>管理员</Text>
          <Switch
            value={this.state.isAdmin}
            onValueChange={value => {
              if (value) {
                this.setState({
                  isAdmin: value,
                  // username: 'admin',
                  // password: 'admin123'
                });

              } else {
                this.setState({
                  isAdmin: value,
                  // username: 'user',
                  // password: 'user123'
                });

              }
            }}
          />
          {/*<Checkbox.Item*/}
          {/*  label="管理员"*/}
          {/*  status={this.state.isAdmin ? 'checked' : 'unchecked'}*/}
          {/*  onPress={() => this.setState({isAdmin: !this.state.isAdmin})}*/}
          {/*/>*/}
        </View>
        <Button mode="contained" title={"登录"} onPress={this.handleLogin}>
          登录
        </Button>
        {/* </View> */}
      </ImageBackground>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
    backgroundColor: '#fff',
  },
  checkboxContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    marginBottom: 10,
  },
});

export default LoginScreen;
